package com.example.lightcontrol;



import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ToggleButton;

public class ControlActivity extends Activity {
	private Handler myHandler = new MyHandler();
	
	private Socket socket;
	
	Map<Integer, SenserState> devices = new Hashtable<Integer, SenserState>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_control);
		// ///////////////////////////////////////////////
		// server codes //
		// ///////////////////////////////////////////////

		this.socket = CommonConfig.getInstance().getSocket();

		TableLayout tableView = (TableLayout) findViewById(R.id.tableLayout);

		String key = "AA:BB:CC:DD:EE:FF";

		devices.put(0, new SenserState(key, 0));

		int dummyDeviceNumber = 8;
		for (int k = 1; k < dummyDeviceNumber; k++) {
			devices.put(k, new SenserState("SS:SS:SS:SS:SS", 0));
		}

		int sequence = 0;
		for (SenserState ss : devices.values()) {
			sequence++;
			TableRow row = new TableRow(this);

			TextView text = new TextView(this);
			ViewGroup.MarginLayoutParams lp = createDefaultMarginLayoutParam();

			text.setLayoutParams(lp);
			text.setText("device#" + sequence);
			text.setTextAppearance(this, android.R.style.TextAppearance_Medium);

			row.addView(text);

			// //////// ToggleButton //////////
			ToggleButton tb = new ToggleButton(this);
			tb.setLayoutParams(this.createDefaultMarginLayoutParam());
			ss.setToggleButton(tb);
			ss.setTextView(text);

			row.addView(tb);
			tableView.addView(row);
		}

		final ToggleButton tb1 = (ToggleButton) findViewById(R.id.toggleButton1);
		addOnClickListener( tb1 );
		
		final ToggleButton tb2 = (ToggleButton) findViewById(R.id.toggleButton2);
		addOnClickListener( tb2 );
		
		final ToggleButton tb3 = (ToggleButton) findViewById(R.id.toggleButton3);
		addOnClickListener( tb3 );
		
		final ToggleButton tb4 = (ToggleButton) findViewById(R.id.toggleButton4);
		addOnClickListener( tb4 );
		
		final ToggleButton tb5 = (ToggleButton) findViewById(R.id.toggleButton5);
		addOnClickListener( tb5 );
		
		final ToggleButton tb6 = (ToggleButton) findViewById(R.id.toggleButton6);
		addOnClickListener( tb6 );

		tableView.requestLayout();
		receive();
		startTimerTask();
	}

	private void addOnClickListener(final ToggleButton tb) {
		tb.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Message msg = new Message();
				if (tb.isChecked()) {
					msg.arg1 = 0;
				} else {
					msg.arg1 = 1;
				}

				msg.what = CommonConfig.MESSAGE_TYPE_LIGH_CONTROL;

				myHandler.sendMessage(msg);
			}
		});
	}

	private MarginLayoutParams createDefaultMarginLayoutParam() {
		MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);

		lp.setMargins(R.dimen.activity_horizontal_margin, 0,
				R.dimen.activity_horizontal_margin, 0);
		return lp;
	}

	protected void startTimerTask() {
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				Message message = new Message();
				message.what = CommonConfig.MESSAGE_TYPE_LIGH_STATE;
				myHandler.sendMessage(message);
			}
		};
		Timer timer = new Timer();
		timer.schedule(task, 100);
	}

	protected void receive() {
		new Thread() {
			public void run() {

				if (socket != null && socket.isConnected()) {
					try {
						DataInputStream input = (DataInputStream) socket
								.getInputStream();

						String got = input.readUTF();
						String[] separated = got.split(",");
						String type = separated[0];
						String value = separated[1];
						if (type.equals("state")) {
							setOnOffState(0, value);
						}

					} catch (Exception e) {
						Log.e("Received", "exception", e);
					}
				}

				try {
					sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}.start();
	}

	protected void setOnOffState(int i, String value) {
		// TODO Auto-generated method stub

	}

	class MyHandler extends Handler {
		public MyHandler() {
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CommonConfig.MESSAGE_TYPE_LIGH_CONTROL:
				if (msg.arg1 == 1) {
					sendMessageOut("open");
				} else if (msg.arg1 == 0) {
					sendMessageOut("close");
				}
				break;
			case CommonConfig.MESSAGE_TYPE_LIGH_STATE:
				sendMessageOut("getState");
				break;
			default:
				break;
			}
		}
	}

	private void sendMessageOut(String command) {
		if (socket != null && socket.isConnected()) {
			try {
				PrintWriter out = new PrintWriter(new BufferedWriter(
						new OutputStreamWriter(socket.getOutputStream())), true);
				out.println(command);
				out.flush();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.control, menu);
		return true;
	}

}
